<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Lib\JwtAuth;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPost as Model;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\WxCircle;
use App\Models\WxPostsGoods;
use App\Models\WxShopAddress;
use App\Models\WxShopCart;
use App\Models\WxShopClassify;
use App\Models\WxShopGoods;
use App\Models\WxShopGoodsProduct;
use App\Models\WxShopNotice;
use App\Models\WxShopService;
use App\Models\WxSlideshow;
use App\Models\WxUser;
use Illuminate\Http\Request;
use Validator;


class ShopController extends BaseController
{

    /**
     * Shop轮播图
     */
    public function banner()
    {
        $banner = WxSlideshow::where('slideshow_state', 1)
            ->where('slideshow_type', 3)->orderBy('sort', 'asc')->get();
        return $this->success($banner);
    }

    /**
     * Shop通知
     */
    public function notice()
    {
        $data = WxShopNotice::where('state', 1)->get(['id', 'title']);
        return $this->success($data);
    }

    /**
     * Shop通知详情
     */
    public function noticeDetail(Request $request)
    {
        $id = $request->id;
        $data = WxShopNotice::where('id', $id)->first();
        return $this->success($data);
    }

    /**
     * Shop分类
     */
    public function classify(Request $request)
    {
        $data = WxShopClassify::where('state', 1)->orderBy('sort', 'asc')
            ->get(['id', 'name']);
        return $this->success($data);
    }

    /**
     * Shop首页板块推荐
     */
    public function plate(Request $request)
    {

        $data = WxShopClassify::where('state', 1)
            ->orderBy('sort', 'asc')->get(['id', 'name', 'is_highlight']);

        $data->map(function ($v) {
            $v->goods = WxShopGoods::where('state', 1)->where('classify_id', $v->id)
                ->orderBy('views', 'desc')
                ->get(['id', 'name', 'pic']);
        });

        return $this->success($data);
    }

    /**
     * Shop首页灵感推荐
     */
    public function inspiration(Request $request)
    {
        $data = WxShopGoods::where('state', 1)
            ->where('is_inspiration', 1)
            ->limit(6)
            ->orderBy('sort', 'asc')
            ->get(['id', 'pic', 'tag', 'name', 'intro', 'vip_price']);
        return $this->success($data);
    }

    /**
     * Shop首页热榜推荐
     */
    public function hotList(Request $request)
    {

        $data = WxShopClassify::where('state', 1)->where('is_hot', 1)
            ->limit(6)->orderBy('sort', 'asc')->get(['id', 'name', 'intro']);

        $data->map(function ($v) {
            $v->goods = WxShopGoods::where('state', 1)->where('classify_id', $v->id)
                ->limit(3)->orderBy('views', 'desc')
                ->get(['id', 'name', 'pic']);
        });

        return $this->success($data);
    }


    /**
     * Shop首页推荐
     */
    public function indexRecommend(Request $request)
    {
        $data = WxShopGoods::where('state', 1)->orderBy('sort', 'asc')
//            ->get(['id', 'pic', 'tag', 'name', 'intro', 'vip_price', 'price']);
            ->paginate(6);

        return $this->success($data);
    }

    /**
     * Shop商品详情
     */
    public function goodsDetails(Request $request)
    {

        $id = $request->id;

        WxShopGoods::where('id', $id)->increment('views');

        $data = WxShopGoods::where('id', $id)->with(['product'])->first();

        // 规格
        $attrs = json_decode($data['sku'], true);
        $data['param_data'] = $this->formatAttrs($attrs['attrs']);

        // 服务
        $data['service'] = WxShopService::whereIn('id', json_decode($data['service_id']))->get(['name', 'intro']);

        return $this->success($data);
    }

    // 处理规格
    private function formatAttrs($attrs)
    {
        foreach ($attrs as $k => $v) {
            foreach ($v as $ks => $vs) {
                $value[] = [
                    'value' => $vs
                ];
            }
            $data[] = [
                'name' => $k,
                'value' => $value
            ];
            $value = [];

        }
        return $data;
    }


    /**
     * Shop分类查询商品
     */
    public function classifyGoodsList(Request $request)
    {

        $cid = $request->cid;

        if ($cid == -1) {
            $data = WxShopGoods::where('state', 1)
                ->orderBy('created_at', 'desc')
                ->paginate(6);
        } else if ($cid == 0) {
            $data = WxShopGoods::where('state', 1)
                ->orderBy('sort', 'asc')
                ->orderBy('views', 'desc')
                ->paginate(6);
        } else {
            $data = WxShopGoods::where('state', 1)->where('classify_id', $cid)
                ->orderBy('sort', 'asc')
                ->paginate(6);
        }

        return $this->success($data);
    }

    /**
     * Shop搜索商品
     */
    public function goodsSearch(Request $request)
    {

        $keyword = $request->keyword;

        $data = WxShopGoods::where('state', 1)
            ->where(function ($query) use ($keyword) {
                $query->orWhere('name', 'like', '%' . $keyword . '%')
                    ->orWhere('intro', 'like', '%' . $keyword . '%')
                    ->orWhere('content', 'like', '%' . $keyword . '%');
            })
            ->orderBy('sort', 'asc')
            ->paginate(6);

        return $this->success($data);
    }

    /**
     * Shop商品晒单
     */
    public function goodsPosts(Request $request)
    {
        $token = $request->header('token');
        $gid = $request->gid;

        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }

        $postsIds = WxPostsGoods::where('goods_id', $gid)->pluck('posts_id');//帖子ID列表

        $data = WxPost::where('is_examine', 1)
            ->where('posts_state', 0)
            ->whereIn('id', $postsIds)
            ->limit(2)->get();

        $data->map(function ($v) use ($uid) {
            $v->user = WxUser::where('id', $v->user_id)
                ->first(['user_avatar', 'user_name', 'id', 'is_member', 'is_official', 'is_authentication', 'gender']);//发帖人
            $v->images = WxPostsImg::where('posts_id', $v->id)->get(['img_url', 'posts_id']);//图片
            $v->video = WxPostsVideo::where('posts_id', $v->id)->first();//视频
            $v->address = WxPostsAddress::where('id', $v->address_id)->first();//地址
            $v->circle = WxCircle::where('id', $v->circle_id)->first(['id', 'circle_name']);//圈子
            $v->like_count = WxLike::where('posts_id', $v->id)->count(); // 帖子喜欢数量
            $v->is_my_posts = Model::isMyPosts($uid, $v->id); // 是否是我的帖子
            $v->is_follow_user = Model::isFollowUser($uid, $v->user_id);// 是否关注该用户
            $v->is_like = Model::isLike($uid, $v->id); // 是否喜欢
            $v->is_collect = Model::isCollec($uid, $v->id); // 是否收藏
            $tagsIds = WxPostsTag::where('posts_id', $v->id)->pluck('tags_id');//标签ID列表
            $v->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);//标签列表
            $v->comment = (new Model())
                ->getComment($v->id, ['user_name', 'comment_content', 'user_id', 'posts_user_id', 'comment_img_url']); // 评论
            $v->comment_count = WxCommentRepositores::commentCount($v->id);//评论数量
        });

        $data->append(['format_time', 'is_ellipsis', 'is_content_beyond']);

        return $this->success($data);
    }

    /**
     * Shop商品晒单
     */
    public function goodsPostsList(Request $request)
    {
        $token = $request->header('token');
        $gid = $request->gid;

        $uid = '';
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }

        $data = PostsRepositores::goodsBaskPosts($uid, $gid);

        return $this->success($data);
    }

    /**
     * Shop添加购物袋
     */
    public function addCart(Request $request)
    {

        $num = $request->num;
        $stock = $request->stock;
        $uid = $request->uid;
        $pid = $request->pid;

        WxShopGoods::where('id', $request->gid)->increment('buys');

        $pstock = WxShopGoodsProduct::where('id', $pid)->value('stock');

        if ($pstock > 0) {

            $isExists = WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)->exists();
            if ($isExists) {
                WxShopCart::where('user_id', $uid)->where('product_id', $pid)
                    ->increment('num', $num);
            } else {
                $model = new WxShopCart();
                $model->user_id = $uid;
                $model->goods_id = $request->gid;
                $model->product_id = $pid;
                $model->goods_pic = $request->pic;
                $model->goods_name = $request->pname;
                $model->goods_product = $request->pvalue;
                $model->price = $request->price;
                $model->vip_price = $request->vip_price;
                $model->num = $num;
                $model->is_check = 1;
                $model->save();
            }

            $pstock = $stock - $num;
            WxShopGoodsProduct::where('id', $pid)->update(['stock' => $pstock]);//减库存

            return $this->success();
        } else {
            return $this->fail(800001);
        }
    }

    /**
     * Shop用户购物袋列表
     */
    public function userCartList(Request $request)
    {
        $uid = $request->uid;

        $pIds = WxShopCart::where('user_id', $uid)->pluck('product_id');//购物袋规格ID列表

        foreach ($pIds as $v) {
            $isExists = WxShopGoodsProduct::where('id', $v)->where('state', 0)->exists();
            if (!$isExists) {
                WxShopCart::where('user_id', $uid)->where('product_id', $v)->where('state', 0)
                    ->update(['state' => 3]);
            }
        }

        $data = WxShopCart::where('user_id', $uid)
            ->whereIn('state', [0,3])
            ->orderBy('created_at', 'desc')
            ->get();

        return $this->success($data);
    }

    /**
     * Shop修改购物袋商品数量
     */
    public function saveCartNum(Request $request)
    {
        $uid = $request->uid;
        $pid = $request->pid;
        $num = $request->num;

        $stock = WxShopGoodsProduct::where('id', $pid)->value('stock');
        $cnum = WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)->value('num');

        if ($stock > $num - $cnum) {
            WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)
                ->update(['num' => $num]);

            $pstock = $stock - ($num - $cnum);
            WxShopGoodsProduct::where('id', $pid)->update(['stock' => $pstock]);//减库存


            return $this->success();
        } else {
            return $this->fail(800002, $stock);
        }
    }

    /**
     * Shop选中购物袋商品
     */
    public function checkCartGoods(Request $request)
    {
        $uid = $request->uid;
        $pid = $request->pid;
        $check = $request->check;

        WxShopCart::where('user_id', $uid)->where('product_id', $pid)->where('state', 0)
            ->update(['is_check' => $check]);

        return $this->success();
    }

    /**
     * Shop全选购物袋商品
     */
    public function allCheckCartGoods(Request $request)
    {
        $uid = $request->uid;
        $is_check = $request->is_check;

        WxShopCart::where('user_id', $uid)->where('state', 0)
            ->update(['is_check' => $is_check]);

        return $this->success();
    }

    /**
     * Shop删除购物袋商品
     */
    public function delCartGoods(Request $request)
    {
        $cid = $request->cid;

        WxShopCart::where('id', $cid)
            ->update(['state' => 1]);

        return $this->success();
    }


    /**
     * Shop用户默认地址
     */
    public function getCheckAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;

        if ($aid == -1) {
            $data = WxShopAddress::where('user_id', $uid)->where('is_check', 1)->where('state', 0)->first();
        } else {
            $data = WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)->first();
        }

        return $this->success($data);
    }

    /**
     * Shop用户地址列表
     */
    public function getAddsList(Request $request)
    {
        $uid = $request->uid;

        $data = WxShopAddress::where('user_id', $uid)->where('state', 0)
            ->orderBy('is_check', 'desc')
            ->orderBy('created_at', 'desc')->get();

        return $this->success($data);
    }

    /**
     * Shop增加/修改地址
     */
    public function saveAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;
        $name = $request->name;
        $mobile = $request->mobile;
        $province = $request->province;
        $city = $request->city;
        $county = $request->county;
        $adds = $request->adds;
        $is_check = $request->is_check;
        if ($is_check == 1) {
            WxShopAddress::where('user_id', $uid)->where('is_check', 1)->where('state', 0)->update(['is_check' => 0]);
        }

        if ($aid == -1) {
            $model = new WxShopAddress();
            $model->user_id = $uid;
            $model->name = $name;
            $model->mobile = $mobile;
            $model->province = $province;
            $model->city = $city;
            $model->county = $county;
            $model->adds = $adds;
            $model->is_check = $is_check;
            $model->save();
        } else {
            WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)
                ->update(['name' => $name,
                    'mobile' => $mobile,
                    'province' => $province,
                    'city' => $city,
                    'county' => $county,
                    'adds' => $adds,
                    'is_check' => $is_check]);
        }

        return $this->success();
    }

    /**
     * Shop用户删除地址
     */
    public function delAdds(Request $request)
    {
        $uid = $request->uid;
        $aid = $request->aid;

        $data = WxShopAddress::where('user_id', $uid)->where('id', $aid)->where('state', 0)
            ->update(['state' => 1]);

        return $this->success($data);
    }

    /**
     * Shop下单商品列表
     */
    public function pliceOrderGoods(Request $request)
    {
        $uid = $request->uid;

        $data = WxShopCart::where('user_id', $uid)->where('is_check', 1)
            ->where('state', 0)
            ->get(['id', 'goods_id', 'goods_name', 'goods_pic', 'goods_product', 'num', 'price', 'product_id', 'vip_price']);

        return $this->success($data);
    }

    /**
     * Shop用户购物袋数量
     */
    public function userCartCount(Request $request)
    {
        $uid = $request->uid;

        $data = WxShopCart::where('user_id', $uid)->where('state', 0)->count();

        return $this->success($data);
    }


}
